package com.von.nhcf.service.impl;

import com.von.nhcf.entity.po.AddressPO;
import com.von.nhcf.entity.po.AddressPOExample;
import com.von.nhcf.entity.po.OrderPO;
import com.von.nhcf.entity.po.OrderProjectPO;
import com.von.nhcf.entity.vo.AddressVO;
import com.von.nhcf.entity.vo.OrderProjectVO;
import com.von.nhcf.entity.vo.OrderVO;
import com.von.nhcf.mapper.AddressPOMapper;
import com.von.nhcf.mapper.OrderPOMapper;
import com.von.nhcf.mapper.OrderProjectPOMapper;
import com.von.nhcf.service.MysqlOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class MysqlOrderServiceImpl implements MysqlOrderService {
    @Autowired
    private OrderProjectPOMapper orderProjectPOMapper;

    @Autowired
    private OrderPOMapper orderPOMapper;

    @Autowired
    private AddressPOMapper addressPOMapper;


    @Override
    public OrderProjectVO getOrderProjectVO(Integer projectId, Integer returnId) {
        return orderProjectPOMapper.selectOrderProjectVO(returnId);
    }

    @Override
    public List<AddressVO> getAddressVOList(Integer memberId) {
        // 获取所有addressPO
        AddressPOExample addressPOExample = new AddressPOExample();
        addressPOExample.createCriteria().andMemberIdEqualTo(memberId);
        List<AddressPO> addressPOS = addressPOMapper.selectByExample(addressPOExample);
        // 转换AddressPO为AddressVO
        List<AddressVO> addressVOS = new LinkedList<>();
        for (AddressPO addressPO : addressPOS) {
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(addressPO, addressVO);
            addressVOS.add(addressVO);
        }

        return addressVOS;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class, readOnly = false)
    public void saveAddressVO(AddressVO addressVO) {
        AddressPO addressPO = new AddressPO();
        BeanUtils.copyProperties(addressVO, addressPO);
        addressPOMapper.insert(addressPO);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class, readOnly = false)
    public void saveOrderVO(OrderVO orderVO) {
        // 保存OrderPO
        OrderPO orderPO = new OrderPO();
        BeanUtils.copyProperties(orderVO, orderPO);
        orderPOMapper.insert(orderPO);
        // 保存OrderProjectPO
        Integer id = orderPO.getId();
        OrderProjectPO orderProjectPO = new OrderProjectPO();
        orderProjectPO.setOrderId(id);
        BeanUtils.copyProperties(orderVO.getOrderProjectVO(), orderProjectPO);
        orderProjectPOMapper.insert(orderProjectPO);
    }
}
